// pages/markerEditPage/markerEditPage.js
import {
  request
} from '../../request/index.js';
import {
  rightJudge
} from '../../lib/right.js';
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 所属图层
    nowLayerName: '',
    nowLayerId: '',
    oldLayerId: '',
    // 名称
    markerName: '',
    // 当前位置
    markerLocation: '',
    // markerID
    markerId: '',
    //数据库查出来的点的信息
    marker: '',
    // rgb值
    markerStyle: '',
    // 标记大小
    markerSize: '',
    // 所有图层信息
    allLayerName: '',
    allLayerId: '',
    // 标记大小范围
    markerSizeRange: ['大', '中', '小'],
    // 更改过后的图层
    modifiedLayerName: '',
    // 更改过后的名称
    modifiedMarkerName: '',
    // 更改过后的样式
    modifiedMarkerStyle: '',
    // 更改过后的大小
    modifiedMarkerSize: '',
    // 更改过后的markerField
    modifiedMarkerField: '',
    // 临时存储
    arr: {},
    // 记录新marker宽度
    newWidth: '',
    // 被选中的图片路径 数组
    chooseImgs: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    this.setData({
      nowLayerName: options.layerName,
      markerName: options.markerName,
      markerLocation: options.location,
      markerId: options.markerId
    })
    // 发起请求获得点的详细信息
    let result = await request({
      url: "/marker/detail/" + parseInt(this.data.markerId)
    })
    if (result.data.data[0].hasOwnProperty("markerField")) {
      this.setData({
        markerDetailInfo: result.data.data[0].markerField
      })
    }
    console.log(result)
    this.setData({
      marker: result.data.data[0],
      nowLayerId: result.data.data[0].layer_id,
      oldLayerId: result.data.data[0].layer_id
    })
    // 赋值
    let markerStyle = ''
    switch (this.data.marker.iconPath) {
      case '../../icons/blue.png':
        markerStyle = 'rgb(80, 130, 204)'
        break;
      case '../../icons/green.png':
        markerStyle = 'rgb(101, 179, 68)'
        break;
      case '../../icons/red.png':
        markerStyle = 'rgb(255,0,0)'
        break;
      case '../../icons/purple.png':
        markerStyle = 'rgb(174, 106, 177)'
        break;
      case '../../icons/orange.png':
        markerStyle = 'rgb(255, 109, 52)'
        break;
      case '../../icons/yellow.png':
        markerStyle = 'rgb(255, 192, 67)'
        break;
      case '../../icons/black.png':
        markerStyle = 'rgb(0,0,0)'
    }
    this.setData({
      markerStyle: markerStyle
    })
    let markerSize = ''
    switch (this.data.marker.width) {
      case 40:
        markerSize = '大'
        break;
      case 30:
        markerSize = '中'
        break;
      case 20:
        markerSize = '小'
    }
    this.setData({
      markerSize: markerSize
    })
    // 取全局数据
    this.setData({
      allLayersData: app.globalData.layerGlobal
    })
    let layerNameArr = []
    let layerIdArr = []
    this.data.allLayersData.map((value) => {
      layerNameArr.push(value.layerName)
      layerIdArr.push(value._id)
    })
    this.setData({
      allLayerName: layerNameArr,
      allLayerId: layerIdArr
    })
    // 发请求获得点的图片
    request({
      url: '/marker/testDownLoad?markerId=' + parseInt(this.data.markerId)
    }).then(result => {
      this.setData({
        chooseImgs: result.data.data
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 切换图层
  pickerLayerChange: async function (e) {
    this.setData({
      nowLayerName: this.data.allLayerName[e.detail.value],
      nowLayerId: this.data.allLayerId[e.detail.value],
      modifiedLayerName: this.data.allLayerName[e.detail.value]
    })
    // 清空数据
    this.setData({
      arr: {}
    })
    // 重新发起请求
    let newlayerFields = ''
    let newMarkerDetailInfo = {}
    // let result = await request({
    //   url: '/layer/' + this.data.nowLayerId
    // })
    // newlayerFields = result.data.data.fieldList
    app.globalData.layerGlobal.map((v, i) => {
      if (v.layerName == this.data.nowLayerName) {
        newlayerFields = v.fieldList
      }
    })
    // 存成键值对
    newlayerFields.map(value => {
      newMarkerDetailInfo[value] = ''
    })
    // 重新设置数据
    this.setData({
      markerDetailInfo: newMarkerDetailInfo
    })
  },
  // 点击选择标记样式
  submit: function () {
    this.setData({
      showModal: true
    })
  },
  close_mask: function () {
    this.setData({
      showModal: false
    })
  },
  setColor: function (e) {
    this.setData({
      markerStyle: e.currentTarget.dataset.color,
      modifiedMarkerStyle: e.currentTarget.dataset.icon,
      showModal: false
    })
  },
  // 输入标记名称
  handleMarkerNameInput: function (e) {
    this.setData({
      modifiedMarkerName: e.detail.value
    })
  },
  // 选择标记大小
  pickerSizeChange(e) {
    this.setData({
      markerSize: this.data.markerSizeRange[e.detail.value],
      modifiedMarkerSize: this.data.markerSizeRange[e.detail.value]
    })
  },
  // 处理输入的其他字段
  inputChange: function (e) {
    let key = e.target.dataset.key;
    let value = e.detail.value;
    this.data.arr[key] = value
    this.setData({
      arr: this.data.arr
    })
  },
  // 保存
  saveNewMarker: async function () {
    if (this.data.markerDetailInfo) {
      let fieldListKeys = Object.keys(this.data.markerDetailInfo)
      fieldListKeys.map(value => {
        if (Object.keys(this.data.arr).includes(value) == false) {
          this.data.arr[value] = this.data.markerDetailInfo[value]
        }
      })
      this.setData({
        modifiedMarkerField: this.data.arr
      })
    } else {
      this.setData({
        modifiedMarkerField: {}
      })
    }
    // 整理数据发送后台
    let sendData = {}
    let newWidth = ''
    switch (this.data.modifiedMarkerSize) {
      case '大':
        newWidth = 40
        break;
      case '中':
        newWidth = 30
        break;
      case '小':
        newWidth = 20
    }
    // 检查是否不变
    if (!this.data.modifiedMarkerName) {
      this.setData({
        modifiedMarkerName: this.data.markerName
      })
    }
    if (!this.data.modifiedLayerName) {
      this.setData({
        modifiedLayerName: this.data.nowLayerName
      })
    }
    if (!newWidth) {
      newWidth = this.data.marker.width
    }
    if (!this.data.modifiedMarkerStyle) {
      this.data.modifiedMarkerStyle = this.data.marker.iconPath
    }
    sendData['width'] = newWidth
    sendData['height'] = newWidth
    sendData['iconPath'] = this.data.modifiedMarkerStyle
    sendData['callout'] = {}
    sendData['callout']['content'] = this.data.modifiedMarkerName
    sendData['callout']['display'] = 'BYCLICK'
    sendData['markerName'] = this.data.modifiedMarkerName
    sendData['layer_name'] = this.data.modifiedLayerName
    sendData['markerField'] = this.data.modifiedMarkerField
    sendData['layer_id'] = this.data.nowLayerId
    // 
    if (this.data.chooseImgs) {
      this.test()
    }
    // let resLayer = await request({
    //   url: '/marker/testZty/' + app.globalData.activeMapIdGlobal,
    // })
    // app.globalData.layerGlobal = resLayer.data.data
    // console.log(app.globalData.layerGlobal)
    let res = await request({
      url: '/marker/modify?markerId=' + this.data.markerId,
      method: 'PUT',
      data: sendData
    })
    // 更新全局数据
    app.globalData.layerGlobal.map((v, i) => {
      if (v._id == this.data.nowLayerId) {
        v.markerList.push(res.data.data)
      }
      if (v._id == this.data.oldLayerId) {
        for (let index = 0; index < v.markerList.length; index++) {
          if (v.markerList[index].id == this.data.markerId) {
            v.markerList.splice(index, 1)
          }
        }
      }
    })
    wx.switchTab({
      url: '../mapPage/mapPage',
    })
  },
  // 图片
  // 点击+触发tap点击事件
  handleChooseImg: function (e) {
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: result => {
        this.setData({
          // 图片数组拼接
          chooseImgs: [...this.data.chooseImgs, ...result.tempFilePaths]
        })
      }
    })
  },
  // 预览图片
  showImg: function (e) {
    const {
      index
    } = e.currentTarget.dataset
    let {
      chooseImgs
    } = this.data
    wx.previewImage({
      urls: this.data.chooseImgs,
      current: this.data.chooseImgs[index]
    })
  },
  handleRemoveImg(e) {
    const {
      index,
      src
    } = e.currentTarget.dataset
    let {
      chooseImgs
    } = this.data
    chooseImgs.splice(index, 1)
    this.setData({
      chooseImgs
    })
    // 发送请求删除图片
    wx.showToast({
      title: '确认要删除图片吗？此操作不可撤回',
      success: res => {
        request({
          url: '/marker/deleteImg?imgUrl=' + src + '&markerId=' + parseInt(this.data.markerId)
        }).then(res => {})
      },
      fail: res => {
        console.log('用户取消删除')
      }
    })
  },
  test() {
    this.data.chooseImgs.forEach((v, i) => {
      console.log(v)
      wx.uploadFile({
        url: 'http://218.28.11.50:7778/api/private/v1/marker/testUpload2?markerId=' + parseInt(this.data.markerId) + '&imgUrl=' + v,
        filePath: v,
        name: 'file',
        formData: {
          'markerId': parseInt(this.data.markerId),
          'imgUrl': v
        },
        success: res => {
          console.log(res)
        }
      })
    })
  }
})